package controllers;

import play.data.validation.Required;
import play.mvc.*;
import com.mysql.jdbc.Connection;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import models.CommunityList;
import models.LogRecord;
import models.RecommendTutorial.*;
import models.RegisteredUser;
import models.Topic;
import models.Tutorial;
import models.membersInCommList.*;
import models.RegisteredUser.*;

public class Topics extends Controller {

	/**
	 * This method renders the topicView page. It displays the topic name, and
	 * also 2 lists of topics. 1 for the available topics to make sub topics,
	 * and the other are the available topics to make parent topicd.
	 * 
	 * @author Rana Amr
	 * @param topicId
	 */
	public static void topicView(long topicId) {
		try {
			Topic currentTopic = Topic.findById(topicId);
			List<Tutorial> tutorials = allTutorials(currentTopic);
			List<Topic> allTopics = Topic.find("id!=?", topicId).fetch();
			List<Topic> currentSub = currentTopic.subTopics;
			List<Topic> newSubs = getNewSubsHelper(allTopics, currentTopic);

			List<Topic> parent = new ArrayList<Topic>();
			List<Topic> myParent = new ArrayList<Topic>();
			for (int i = 0; i < allTopics.size(); i++) {
				List<Topic> Sub = allTopics.get(i).subTopics;
				if (Sub.isEmpty()) {
					parent.add(allTopics.get(i));
					continue;
				} else {
					for (int j = 0; j < Sub.size(); j++) {
						if (Sub.get(j).id != topicId) {
							parent.add(allTopics.get(i));
						} else {
							myParent.add(allTopics.get(i));
							continue;
						}
					}
				}
			}
			newSubs = finalSubTopicList(newSubs, myParent);
			parent = finalParentTopicList(parent, currentSub);
			render(currentTopic, tutorials, allTopics, currentSub, newSubs,
					parent);
		} catch (Exception e) {
			renderText("You need to log in");
		}
	}

	/**
	 * This method returns all the tutorials of the current topic that are
	 * published or draft if the user is the creator, a contribter or reviewe.
	 * 
	 * @author Rana Amr
	 * @param currentTopic
	 * @return List<Tutorial>
	 */
	public static List<Tutorial> allTutorials(Topic currentTopic) {
		long uid = Long.parseLong(session.get("RegisteredUserId"));
		RegisteredUser user = RegisteredUser.findById(uid);
		List<Tutorial> tutorials = currentTopic.tutorials;
		List<Tutorial> finalTutorials = new ArrayList<Tutorial>();
		
		for (int i = 0; i < tutorials.size(); i++) {
			if (tutorials.get(i).status.equals("publish")) {
				System.out.println(i);
				finalTutorials.add(tutorials.get(i));
				continue;
			} else {
				if (tutorials.get(i).creator == user
						|| (tutorials.get(i).getContributorsList()
								.contains(user)) || user.isReviewer) {
					finalTutorials.add(tutorials.get(i));
					continue;
				} else {
					System.out.println(i);
					continue;
				}
			}
		}
		return finalTutorials;
	}

	/**
	 * This method is a helper method to return the Sub Topics that will be
	 * displayed in the topicView page.
	 * 
	 * @author Rana Amr
	 * @param allTopics
	 * @param currentTopic
	 * @return List<Topic>
	 */
	public static List<Topic> getNewSubsHelper(List<Topic> allTopics,
			Topic currentTopic) {
		List<Topic> currentSub = currentTopic.subTopics;
		List<Topic> newSubs = new ArrayList<Topic>();
		for (int i = 0; i < allTopics.size(); i++) {
			if (currentSub.isEmpty()) {
				newSubs.add(allTopics.get(i));
				continue;
			} else {
				for (int j = 0; j < currentSub.size(); j++) {
					if (allTopics.get(i).id != currentSub.get(j).id) {
						newSubs.add(allTopics.get(i));
					} else {
						continue;
					}
				}
			}
		}
		return newSubs;
	}

	/**
	 * This method is a helper method to return the final Sub Topics that will
	 * be displayed in the topicView page.
	 * 
	 * @author Rana Amr
	 * @param newSubs
	 * @param myParent
	 * @return List<Topic>
	 */
	public static List<Topic> finalSubTopicList(List<Topic> newSubs,
			List<Topic> myParent) {
		for (int i = 0; i < newSubs.size(); i++) {
			for (int j = 0; j < myParent.size(); j++) {
				if (newSubs.get(i).id == myParent.get(j).id) {
					newSubs.remove(i);
					continue;
				}
			}
		}
		return newSubs;
	}

	/**
	 * This method is a helper method to return the final Parent Topics that
	 * will be displayed in the topicView page.
	 * 
	 * @author Rana Amr
	 * @param parent
	 * @param currentSub
	 * @return List<Topic>
	 */
	public static List<Topic> finalParentTopicList(List<Topic> parent,
			List<Topic> currentSub) {
		for (int i = 0; i < parent.size(); i++) {
			for (int j = 0; j < currentSub.size(); j++) {
				if (parent.get(i).id == currentSub.get(j).id) {
					parent.remove(i);
					continue;
				}
			}
		}
		return parent;
	}

	/**
	 * This method renders the createTopic page.
	 * 
	 * @author Rana Amr
	 */
	public static void createTopic() {
		render();
	}

	/**
	 * This method creates a new topic. It first checks for any duplicates, and
	 * if no duplicates were found, then a new topic is created.
	 * 
	 * @author Rana Amr
	 * @param name
	 */
	public static void createNewTopic(
			@Required(message = "Please enter a name for your New Topic") String name) {
		if (validation.hasErrors()) {
			params.flash();
			validation.keep();
			createTopic();
		} else {

			List<Topic> x = Topic.find("topicName=?", name).fetch();
			if (x.isEmpty()) {
				models.Topic top = new models.Topic(name);
				top.save();
				// Logging ....
				long uid = Long.parseLong(session.get("RegisteredUserId"));
				RegisteredUser u = RegisteredUser.findById(uid);
				LogRecord.createLog("Create new Topic : " + top.topicName, u);
				topicView(top.id);

			} else {
				renderText("There is an already existing topic with this name!");
			}
		}
	}

	/**
	 * This method takes the current topic and the chosen topic and sets the
	 * chosen topic as a subtopic for the current topic. And then renders the
	 * topicView page of the current topic.
	 * 
	 * @author Rana Amr
	 * @param topicId
	 * @param subTopicId
	 */
	public static void addSubTopic(long topicId, long subTopicId) {
		Topic currentTopic = Topic.findById(topicId);
		Topic subTopic = Topic.findById(subTopicId);
		currentTopic.setSubTopic(subTopic);
		topicView(topicId);
	}

	/**
	 * This method takes the current topic and the chosen topic and sets the
	 * current topic as a subtopic for the chosen topic. And then renders the
	 * topicView page of the chosen topic.
	 * 
	 * @author Rana Amr
	 * @param topicId
	 * @param parentTopicId
	 */
	public static void addParentTopic(long topicId, long parentTopicId) {
		Topic currentTopic = Topic.findById(topicId);
		Topic parentTopic = Topic.findById(parentTopicId);
		parentTopic.setSubTopic(currentTopic);
		topicView(parentTopicId);
	}

	/*
	 * This method retrieves the Title of the topic in use and checks whether
	 * the current user is following this topic or not. If yes, a message will
	 * appear to the user that he's already following this topic. If not, the id
	 * of the user and the id of the topic are added to the table followTopic
	 * that specifies which user is following which topic, and a message will
	 * appear to the user that he successfully followed this topic.
	 * 
	 * @author Marwa
	 */
	// public static void followTopic()throws SQLException{
	// if (session.get("RegisteredUserId") != null && session.get("topicID") !=
	// null){
	// long fid = Long.parseLong(session.get("RegisteredUserId"));
	// long tid = Long.parseLong(session.get("topicID"));
	// Topic to = Topic.findById(tid);
	// String name = to.topicName;
	// List<followTopic> ft =
	// followTopic.find("followerID =? and followedTopID =? and topName=?",
	// fid,tid,name).fetch();
	// if(ft.isEmpty()){
	// new followTopic(fid, tid, name);
	// renderText("You have successfully followed this Topic");
	// }else{
	// renderText("You Are already following this Topic");
	// }
	// }
	//
	// }

	/**
	 * This method it renders text when the user is already following this
	 * topic, and when the user has successfully followed this topic.
	 * 
	 * @param tId
	 *            which is the id of the followed topic.
	 * @return rendered Text if the user is not logged in, if he's already
	 *         following this topic and if he successfully followed the topic
	 * 
	 * @author Marwa
	 */
	public static void followTop(long tId) {
		if (session.get("RegisteredUserId") != null) {
			long userId = Long.parseLong(session.get("RegisteredUserId"));
			Topic topic = Topic.findById(tId);
			boolean result = topic.followTopic(userId, tId);
			if (result == true) {
				renderText("You have successfully followed this Topic");
			} else {
				renderText("You Are already following this Topic");
			}
		} else {
			renderText("You must Log in first to follow a topic!!");
		}
	}

	/**
	 * this method returns a list of followed topics it contains a condition
	 * were it checks first if it is the registered user who is viewing or
	 * others
	 * 
	 * @author Nada
	 * @param viewOthers
	 */

	public static void followedTopicPage(long viewOthers) {
		long registeredUserId = Long.parseLong(session.get("RegisteredUserId"));
		RegisteredUser user = RegisteredUser.findById(registeredUserId);
		RegisteredUser otherUser = RegisteredUser.findById(viewOthers);
		if (user != otherUser) {
			List<Topic> followedTopics = otherUser
					.viewFollowedTopics(otherUser.id);
			render(followedTopics);

		}

		else {
			List<Topic> followedTopics = user
					.viewFollowedTopics(registeredUserId);
			render(followedTopics);
		}
	}

	/**
	 * This method renders a list of topics for the tagCloud
	 * 
	 * @author Renad
	 */
	public static void main() {
		List<Topic> topics = Topic.find("order by topicName asc").fetch();
		render(topics);
	}

	/***
	 * This method is for listing all the merged topics and displaying them on
	 * the topic view list
	 * 
	 * @param mergedTopics
	 * @return
	 */
	public static List<Topic> mergedTopicsList(List<Topic> mergedTopics) {
		for (int i = 0; i < mergedTopics.size(); i++) {
			continue;
		}
		return mergedTopics;
	}

	/**
	 * This method if for adding the merged topics of the tutorial only if the
	 * user is a housekeeper
	 * 
	 * @author Nourhan Elmalahy
	 * @param topicId
	 * @param mergedTopicId
	 */
	public static void addMergedTopic(long topicId, long mergedTopicId) {
		Topic currentTopic = Topic.findById(topicId);
		Topic mergeTopic = Topic.findById(mergedTopicId);
		long userId = Long.parseLong(session.get("RegisteredUserId"));
		RegisteredUser user = RegisteredUser.findById(userId);
		if (user.isHousekeeper() == true) {
			currentTopic.addMergedTopic(mergeTopic);
		} else
			renderText("You are not authorized to merge these topic");
		topicView(topicId);
	}
	/***
	 * End Nourhan Elmalahy
	 */
}
